package com.wxcms.ctrl;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.core.util.UDPClient;
import com.his.domain.PicSource;
import com.his.service.PicSourceService;
import com.wxcms.domain.DepEquipments;
import com.wxcms.domain.DodemWxCpUser;
import com.wxcms.domain.WxCpMyConfigStorage;
import com.wxcms.domain.Wxprovinceids;
import com.wxcms.mapper.EquipmentDao;
import com.wxcms.mapper.WxCpDepartDao;
import com.wxcms.mapper.WxCpUserDao;
import com.wxcms.mapper.WxprovinceidsDao;
import com.wxcms.service.MyWxCpService;
import com.wxcms.service.impl.DodemWxServer;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.cp.api.WxCpConfigStorage;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.bean.WxCpMessage.WxArticle;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
 
@Controller
@RequestMapping()
public class WxCpCtrl {

	Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private WxCpDepartDao depdao;

	@Autowired
	private WxCpUserDao userdao;

	@Autowired
	private MyWxCpService myWxCpService;

	@Autowired
	private EquipmentDao equipdao;

	@Autowired
	private PicSourceService picSourceService;
	
	@Autowired
	private WxprovinceidsDao weatherDao;

	public WxCpCtrl() {
		/*
		 * config = new WxCpInMemoryConfigStorage();
		 * 
		 * config.setCorpId("wx27362885178c643b"); // 设置微信企业号的appid
		 * config.setCorpSecret(
		 * "U_nBClHfQGmbEPYB4y2eYoThgqzLhUkxRYWXMSClXdQjYig3DuYE1I076DaKfQzs");
		 * // 设置微信企业号的app // corpSecret config.setAgentId("2"); // 设置微信企业号应用ID
		 * config.setToken("xlssxj"); // 设置微信企业号应用的token
		 * config.setAesKey("gHoO578nMSsegY0CrxwKKOcWXfKgPap1gDoaVA3oZgd"); //
		 * 设置微信企业号应用的EncodingAESKey
		 */

		// List<WxCpMyConfigStorage> config1=configStorageDao.getbyagentId("2");
		//
		// wxCpService = new WxCpServiceImpl();
		//
		// wxCpService.setWxCpConfigStorage((WxCpConfigStorage) config1.get(0));

		// initRouter();

		// wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
		// wxCpMessageRouter.rule().async(false).content("哈哈") // 拦截内容为“哈哈”的消息
		// .handler(handler).end();
	}
	@RequestMapping(value = "/getServices")
	public @ResponseBody JSONArray getServices(HttpServletRequest request){
		JSONArray  arr = new JSONArray (); 
//		 Collection<DodemWxServer>    services=myWxCpService.getWxCpServices();
//		 obj.parseArray(arg0);
 	      List<WxCpMyConfigStorage> res =myWxCpService.getAllProvinceInfo("");
 	     for(WxCpMyConfigStorage cf:res){
 	    	JSONObject obj = new JSONObject(); 
 	    	obj.put("name", cf.getName());
 	    	obj.put("province", cf.getProvince());
 	    	obj.put("url", cf.getUrl());
 	    	obj.put("icon", cf.getCorpicon());
 	    	obj.put("name", cf.getProvincename());
 	    	arr.add(obj);
 	     }
 	      
 	      
		return arr;
	}
	@RequestMapping(value = "/getPushs")
	public @ResponseBody JSONObject getpushs(HttpServletRequest request) throws WxErrorException {
		JSONObject obj = new JSONObject();
	    Collection<DodemWxServer>    services=myWxCpService.getWxCpServices();
		List<DepEquipments> lus = equipdao.getPushNeeded();
		int len = lus.size();
		for (int i = 0; i < len; i++) {
			DepEquipments dep = lus.get(i);
			String puid=dep.getPuid();
			String name=equipdao.getEquipName(puid);
			obj.put("success", dep.toString());
			List<PicSource> pics = picSourceService.getPics("PICTURE", puid, dep.getPushTime()/1000,1);
			
			if(pics.size()<0){
				if(dep.getIsforce()==1){
					pics = picSourceService.getPics("PICTURE", puid, dep.getLastTime()/1000-2,1);
				}
				
			}
			obj.put("corpid_"+dep.getPuid(), dep.getCorpId());
			obj.put("len_"+dep.getPuid(), pics.size());

		    if(pics.size()>0){
		    	
		    	for( DodemWxServer server:services){
		    		 String corpid=   server.getConfig().getCorpId();
		    		 String toket=   server.getConfig().getToken();
		    		 
		    		 obj.put(corpid, toket);
		    		if( dep.getCorpId().contains(corpid)&&(toket=="real")){
		    		 
						PicSource pic=pics.get(0);
						
						WxArticle article1 = new WxCpMessage.WxArticle();
						String httpPath= "http://" + request.getServerName() +"/"+request.getContextPath();
						System.out.println(httpPath+ "/mindex");
						String _ul = httpPath+  "/mindex?puid="+puid;
	 
						log.info(_ul);
			
						String _wxul = server.oauth2buildAuthorizationUrl(_ul, "test");
			
						article1.setUrl(_wxul);
			
						article1.setPicUrl(httpPath+ "/equip/picsrc/"+pic.getPath()+pic.getName());
						
						log.info(httpPath + "/equip/picsrc/"+pic.getPath());
						
						article1.setDescription(puid);
						article1.setTitle(name + "\n" + pic.getTime());
						String depids = depdao.getDepIds(puid,corpid);
						
						System.out.println(depids);
						
						WxCpMessage m = WxCpMessage.NEWS().agentId(server.getConfig().getAgentId()).toParty(depids)
								.addArticle(article1).build();
						
						server.messageSend(m);	
						
					    equipdao.updatePushTime(puid,""+pic.getTtime().getTime()/1000);
 
				         article1=null;
		    		}
		    	}
		    }
		  //  slist.add(puid);
	
		}
		
/*		//更新已经推送的时间
		if(slist.size()>0) 
	        equipdao.updatePushTime(StringUtils.join(slist, "|"));*/
		return obj;
	}

	/**
	 * 
	 * 根据参数设备PUID抓取设备图片
	 * 
	 */
	@RequestMapping(value = "/getvedio/{puid}")
	public @ResponseBody JSONObject getvedio(@PathVariable String puid) {
		JSONObject obj = new JSONObject();
		UDPClient udp = new UDPClient("127.0.0.1", 5123);
		obj.put("success", udp.getVedio(puid));
		udp=null;     
		return obj;
	}

	/**
	 * 
	 * 根据参数设备PUID抓取设备图片
	 * 
	 */
	@RequestMapping(value = "/getpic/{puid}")
	public @ResponseBody JSONObject getpic(@PathVariable String puid) {
		JSONObject obj = new JSONObject();
		UDPClient udp = new UDPClient("127.0.0.1", 5123);
		obj.put("success", udp.getCurrentPic(puid));
		udp=null;  
		return obj;
	}

//	/**
//	 * POST 请求：进行消息处理；
//	 */
//	@RequestMapping(value = "/message", method = RequestMethod.POST)
//	public @ResponseBody String doPost(HttpServletRequest request, HttpServletResponse response) {// ,@PathVariable
//																									// String
//																									// account
//		String result = null;
//		String msgSignature = request.getParameter("msg_signature");
//		String nonce = request.getParameter("nonce");
//		String timestamp = request.getParameter("timestamp");
//		String echostr = request.getParameter("echostr");
//		// 处理用户和微信公众账号交互消息
//		WxCpXmlMessage inMessage = null;
//		try {
//			inMessage = WxCpXmlMessage.fromEncryptedXml(request.getInputStream(), myWxCpService.getConfig(), timestamp,
//					nonce, msgSignature);
//			myWxCpService.setRequest(request);
//			WxCpXmlOutMessage outMessage = myWxCpService.getWxCpMessageRouter().route(inMessage);
//			System.out.println("inMessage=================\n" + inMessage.getContent());
//			if (outMessage != null) {
//				// response.getWriter().write(outMessage.toEncryptedXml(myWxCpService.getConfig()));
//				result = outMessage.toEncryptedXml(myWxCpService.getConfig());
//			}
//			// return;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			result = e.getMessage();
//		}
//		inMessage = null;
//		return result;
//
//	}

	// name:_name,time:_time,src:_src,puid:_puid,url:_url}
	@RequestMapping(value = "/push/{province}/{token}")
	public @ResponseBody JSONObject push(HttpServletRequest request
			,@PathVariable String province,@PathVariable String token,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "time", required = true) String time,
			@RequestParam(value = "src", required = true) String src,
			@RequestParam(value = "puid", required = true) String puid,
			@RequestParam(value = "url", required = true) String url,
			@RequestParam(value = "tlong", required = true) String tlong) {
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, token);
		JSONObject obj = new JSONObject();
		if(request.getSession().getAttribute("uname")==null){
			
			obj.put("success", false);
			obj.put("desc","未登陆，或登陆超时!");
			
		}
		else{
			WxArticle article1 = new WxCpMessage.WxArticle();
	
			System.out.println(request.getScheme() + "://" + request.getServerName() + url);
			String _ul = request.getScheme() + "://" + request.getServerName() + url + "&name=" + name;
	
			String _wxul = myService.oauth2buildAuthorizationUrl(_ul, "test");
	
			System.out.println("==========" + _wxul);
	
			article1.setUrl(_wxul);
	
			article1.setPicUrl(request.getScheme() + "://" + request.getServerName() + src);
			String sdname=request.getSession().getAttribute("uname").toString();
			String position =request.getSession().getAttribute("position").toString();
			if (position == null)
				position = "";
			
			 if(position.contains("admin"))
				 sdname="系统自动推送";
	
			article1.setDescription("设备号："+puid + "\n发送人：" + sdname );
			article1.setTitle( equipdao.getEquipName(puid)+ "\n" + time);// .toUser("yangyufan")
																											// .toUser("@all")
	
			// 只推送给指定用户
			System.out.println("======================\n");
			String depids = depdao.getDepIds(puid,myService.getConfig().getCorpId());
			System.out.println(depids);
	
			if (depids.startsWith("|"))
				depids = depids.substring(1).trim();
	
			try {
				if (!depids.isEmpty()) {
					//所有推送都会推给公司的人员
					WxCpMessage m = WxCpMessage.NEWS().agentId(myService.getConfig().getAgentId()).toParty(depids)
							.addArticle(article1).build();
					myService.messageSend(m);
					obj.put("success", true);
					m=null;
				} else
					obj.put("success", false);
			} catch (WxErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				obj.put("success", false);
			}
			article1=null;
		
		}

		return obj;
	}

	/**
	 * 读取 部门和成员信息 并保存到数据库中
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws WxErrorException
	 */
	@RequestMapping(value = "/getDepart")
	public @ResponseBody JSONObject getDepart(HttpServletRequest request,@RequestParam(value = "province", defaultValue = "0") String province  )
			throws UnsupportedEncodingException, WxErrorException {
		JSONObject obj = new JSONObject();
		if(province==null)
			province=request.getSession().getAttribute("province").toString();
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, "real");
		
		try {
			myWxCpService.SyncDepartFromWeiXin(myService);
			 
			 obj.put("success", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			obj.put("success", false);
		}

		return obj;
	}

	/**
	 * 根据 agentid 读取 企业应用 的所有信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws WxErrorException
	 */
	@RequestMapping(value = "/readCorpInfo/{province}/{token}")
	
	public @ResponseBody JSONObject readCorpInfo(@PathVariable String province,@PathVariable String token) throws WxErrorException{
 
		JSONObject obj = myWxCpService.getappinfo(province,token); 

		return obj;
	}
	//从服务器获取应用信息
     @RequestMapping(value = "/syncAgentInfo")
	
	public @ResponseBody JSONObject sync() throws WxErrorException{
 
         return  myWxCpService.syncAgentInfo();
 		 
	}


	/**
	 * 确认登录
	 * 
	 * 
	 */
	@RequestMapping(value = "/confirmlogin")
	public @ResponseBody JSONObject confirmlogin(@RequestParam(value = "time", defaultValue = "0") String time,
			@RequestParam(value = "mobile", defaultValue = "") String mobile,
			@RequestParam(value = "email", defaultValue = "") String email,
			@RequestParam(value = "weixinid", defaultValue = "") String weixinid,
			@RequestParam(value = "province", defaultValue = "0") String province,
			@RequestParam(value = "corpid", defaultValue = "0") String corpid) {
		JSONObject obj = new JSONObject();

		try {
			//登录信息设置，根据获取的微信企业号用户信息，mobile email weixinid 其中之一，设置当前登录的时间标识和登录的企业号的corpid
			userdao.updateUser(time, corpid,province,mobile,email,weixinid); 

			obj.put("success", true);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			obj.put("success", false);
		}

		return obj;

	}

	@RequestMapping(value = "/logout")
	public @ResponseBody JSONObject logout(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jobj = new JSONObject();

		try {
			request.getSession().invalidate();
			jobj.put("success", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jobj.put("success", false);
		}

		return jobj;
	}

	/**
	 * 确认登录 PC端循环扫描
	 * 
	 * 
	 */
	@RequestMapping(value = "/checkForResult")
	public @ResponseBody JSONObject checkForResult(HttpServletRequest request,
			@RequestParam(value = "time", defaultValue = "0") String time) throws UnsupportedEncodingException {
		JSONObject jobj = new JSONObject();
	 
		if (request.getAttribute("getcodeOk") != null) {
			jobj.put("getcodeOk", false);
		}

		try {

			List<DodemWxCpUser> lu = userdao.checkUserByTime(time);

			if (lu.size() > 0) {
				jobj.put("success", true);
				String position = lu.get(0).getPosition();
				if (position == null)
					position = "";
				 Integer[] ids=lu.get(0).getDepartIds();
				 StringBuilder arrayString = new StringBuilder();
				 for (int j = 0, l = ids.length; j < l; j++) {
			            arrayString.append(ids[j]);
			            if (j < l - 1) {
			                arrayString.append(",");
			            }
			        }
				request.getSession().setAttribute("depidstr", arrayString);
				// 扫码登录成功 将登录用户数据放入session 中
				request.getSession().setAttribute("userid", lu.get(0).getUserId());
				request.getSession().setAttribute("depids", lu.get(0).getDepartIds());
				request.getSession().setAttribute("uname", lu.get(0).getName());
				request.getSession().setAttribute("icon", lu.get(0).getAvatar());
				request.getSession().setAttribute("departids", lu.get(0).getDepartIds());
				
				request.getSession().setAttribute("province", lu.get(0).getLoginprovince());	
				request.getSession().setAttribute("corpid", lu.get(0).getCorpid());
				
				request.getSession().setAttribute("position", position);
				request.getSession().setAttribute("positiond", position.contains("admin") ? "true" : "false");
				
				jobj.put("province", lu.get(0).getLoginprovince());
				String _corpid=lu.get(0).getCorpid();
				jobj.put("corpid", _corpid);
				
			    List<WxCpMyConfigStorage> res =myWxCpService.getAllProvinceInfo(_corpid);
				
			    request.getSession().setAttribute("corpicon", res.get(0).getCorpicon());
			    
			} else
				jobj.put("success", false);
			    
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			jobj.put("success", false);
		}

		return jobj;
	}
	
	 

	/***
	 * 手机客户端二维码登录
	 * 
	 */
	@RequestMapping(value = "/getoath/{province}")
	public @ResponseBody ModelAndView getoath(HttpServletRequest request,@PathVariable String province )
			throws UnsupportedEncodingException, WxErrorException {

		ModelAndView modelAndView = new ModelAndView("wxweb/subscribe");//oathqrcode

		String code;
		System.out.println(code = request.getParameter("code"));
		System.out.println(request.getParameter("state"));

		request.setAttribute("getcodeOk", true);

		// 读取二维码中的时间信息，连同 用户名 写入数据库，标示当前用户通过该二维码 扫码登录了
		String time;
		System.out.println(time = request.getParameter("time"));
		if (code != null) {
			//需要遍历 所有配置的 ，服务避免由于服务没有该人 不能正确的验证服务。
			  DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province,"real");
			   
			  DodemWxCpUser user = myWxCpService.getUser(myService,code);
		    	//WxCpUser user = myWxCpService.getAvailableUser(code);
			  
			log.info("================================" + user);	
			if (user != null) {
				 modelAndView = new ModelAndView("wxweb/getoath");
				
				 
		 	   JSONObject obj = myWxCpService.getappinfo(province,"real");
				//根据用户查询该用户所有关注的企业号 
			  //  List<WxCpMyConfigStorage> configs =	myWxCpService.getConfigByUserMobile(user.getMobile(),user.getEmail(),user.getWeiXinId());
 			    modelAndView.addObject("cfg",myService.getConfig());
				
				
				// 应用的图标
			 	modelAndView.addObject("appicon", obj.get("square_logo_url").toString().replace("/0", "/64"));
				// 应用的名称
			 	modelAndView.addObject("appname", obj.get("name").toString());
				
			
				
				// 应用的用户 ，userid 为企业号内部唯一标示，不可更改。
			    // 添加的时候设置的，多企业号验证的时候可能会出现，相同的人的userid不一样，但是userid又不能够更改，故不采用userid 作为多企业号的验证标识。
				 modelAndView.addObject("userid", user.getUserId());
			    
			    modelAndView.addObject("mobile", user.getMobile());
			    modelAndView.addObject("email", user.getEmail());
			    modelAndView.addObject("weixinid", user.getWeiXinId());
			    
				// 应用的用户
				modelAndView.addObject("uname", user.getName());
				
				// 应用的用户头像
				modelAndView.addObject("uicon", user.getAvatar());
				
				// time
				modelAndView.addObject("time", time);
				

			

			} else
			// 判断用户是否存在，不存在给出添加关注二维码
			{   //邀请审批的 二维码
				log.error("用户不存在，没关注！"); 
				
			    modelAndView.addObject("cfg",myService.getConfig());
				
				
				
				
			}
		}
		return modelAndView;
	}

	@RequestMapping(value = "/OATH")
	public @ResponseBody String oath(HttpServletRequest request,@PathVariable String province,@PathVariable String token) throws UnsupportedEncodingException {
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, token);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		url += "appid=" + myService.getConfig().getCorpId();
		url += "&redirect_uri=" + URIUtil.encodeURIComponent("http://pop.dongdiankeji.com/qyweix/getoath");
		url += "&response_type=code";
		url += "&scope=snsapi_userinfo";
		Object state = "TEST";
		if (state != null) {
			url += "&state=" + state;
		}
		url += "#wechat_redirect";
		return url;
		// ByteArrayOutputStream out = QRCode.from(url).to(
		// ImageType.PNG).stream();
		// return out
		// return url;//
	}

	/**
	 * 生成登陆二维码
	 * 
	 */
	@RequestMapping(value = "/oathCode")///{province}/{token},@PathVariable String province,@PathVariable String token
	public ModelAndView videoView(HttpServletRequest request) { 
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT("dtest", "real");
		// 获取时间戳 用于标示 二维码的唯一性
//		Timestamp d = new Timestamp(System.currentTimeMillis());

		ModelAndView modelAndView = new ModelAndView("wxweb/oathqrcode");
		
//		// 形成跳转url
//		
//		String url1 = myService.oauth2buildAuthorizationUrl(
//				request.getScheme() + "://" + request.getServerName() + "/qyweix/getoath?" + "time=" + (d.getTime()/1000),
//				"TEST");
//		
//		// 跳转url 生成 二维码 提供微信扫描 登录
//		ByteArrayOutputStream out = QRCode.from(url1).withSize(320, 320).to(ImageType.PNG).stream();
//		modelAndView.addObject("img", new String(Base64.encodeBase64(out.toByteArray())));
//
//		modelAndView.addObject("time", d.getTime()/1000);

		return modelAndView;
	}
	@RequestMapping(value = "/codeImg")///{province}/{token},@PathVariable String province,@PathVariable String token
	public @ResponseBody JSONObject codeImg(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "province") String province,@RequestParam(value = "province") String token) { 
		JSONObject jobj = new JSONObject();
		
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, "real");
		// 获取时间戳 用于标示 二维码的唯一性
		Timestamp d = new Timestamp(System.currentTimeMillis());
 
		
		// 形成跳转url
		
		String url1 = myService.oauth2buildAuthorizationUrl(
				request.getScheme() + "://" + request.getServerName() + "/qyweix/getoath/"+province + "?time=" + (d.getTime()/1000),
				d.getTime()/1000+"");
		
		// 跳转url 生成 二维码 提供微信扫描 登录
		ByteArrayOutputStream out = QRCode.from(url1).withSize(320, 320).to(ImageType.PNG).stream();
	/*	modelAndView.addObject("img", new String(Base64.encodeBase64(out.toByteArray())));

		modelAndView.addObject("time", d.getTime()/1000);*/
		jobj.put("img",  new String(Base64.encodeBase64(out.toByteArray())));
		jobj.put("time", d.getTime()/1000);
//		try {
//			response.getOutputStream().write( Base64.encodeBase64(out.toByteArray()));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

	     return jobj;
	}
	
	/**
	 * 创建菜单
	 * 
	 */
	@RequestMapping(value = "/createmenu/{province}/{token}")
	public @ResponseBody JSONObject createmenu(HttpServletRequest request,@PathVariable String province,@PathVariable String token) {

		JSONObject obj = new JSONObject();

		WxMenu wxMenu = new WxMenu();
		{
			WxMenuButton btn = new WxMenu.WxMenuButton();
			btn.setName("设备巡检");
			// btn.setKey("devices");
			btn.setType(WxConsts.BUTTON_VIEW);
			// 获取时间戳 用于标示 二维码的唯一性
			Timestamp d = new Timestamp(System.currentTimeMillis());
			
			String url1 = myWxCpService.getWxCpServiceByPT(province, token).oauth2buildAuthorizationUrl(
					request.getScheme() + "://" + request.getServerName() + "/qyweix/mindex/" +province+ "?time=" + d.getTime()/1000,
					"TEST");
			btn.setUrl(url1);
			wxMenu.getButtons().add(btn);
		}
		{
			WxMenuButton btn = new WxMenu.WxMenuButton();
			btn.setName("设备列表");
			// btn.setKey("devices");
			btn.setType(WxConsts.BUTTON_CLICK);
			// 获取时间戳 用于标示 二维码的唯一性
			btn.setKey("wx_equipList");

			// Timestamp d = new Timestamp(System.currentTimeMillis());
			// String url1 =
			// myWxCpService.getWxCpService().oauth2buildAuthorizationUrl(
			// request.getScheme() + "://" + request.getServerName()
			// +"/qyweix/mindex?" + "time=" + d.getTime(), "TEST");
			// btn.setUrl(url1);
			wxMenu.getButtons().add(btn);
		}

		WxMenuButton btn1 = new WxMenu.WxMenuButton();
		btn1.setName("辅助功能");
		// btn1.setKey("_k_real1");
		// btn1.setType(WxConsts.BUTTON_CLICK);

		List<WxMenuButton> subButtons = new ArrayList<WxMenuButton>();
		{
			WxMenuButton btn2 = new WxMenu.WxMenuButton();
			btn2.setName("二维码识别");
			btn2.setType(WxConsts.BUTTON_SCANCODE_WAITMSG);
			btn2.setKey("push_menu");
			subButtons.add(btn2);
		}

		{
			WxMenuButton btn2 = new WxMenu.WxMenuButton();
			btn2.setName("二维码扫描");
			btn2.setType(WxConsts.BUTTON_SCANCODE_PUSH);
			btn2.setKey("pc_code");
			subButtons.add(btn2);
		}

		{
			WxMenuButton btn2 = new WxMenu.WxMenuButton();
			btn2.setName("成员信息");
			btn2.setType(WxConsts.BUTTON_CLICK);
			btn2.setKey("wx_menber");
			subButtons.add(btn2);
		}

		{
			WxMenuButton btn2 = new WxMenu.WxMenuButton();
			btn2.setName("帮助");
			btn2.setType(WxConsts.BUTTON_CLICK);
			btn2.setKey("help");
			subButtons.add(btn2);
		}

		btn1.setSubButtons(subButtons);

		wxMenu.getButtons().add(btn1);

		// 设置菜单
		try {
			myWxCpService.getWxCpServiceByPT(province,token).menuCreate(wxMenu);
			obj.put("success", true);

		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			obj.put("success", false);
		}

		return obj;
	}

	/**
	 * GET请求：进行URL、Tocken 认证； 1. 将token、timestamp、nonce三个参数进行字典序排序 2.
	 * 将三个参数字符串拼接成一个字符串进行sha1加密 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信 , method
	 * = RequestMethod.GET,method = RequestMethod.GET
	 */
	@RequestMapping(value = "/message/{province}/{token}" )
	public @ResponseBody String doPost(HttpServletRequest request,@PathVariable String province,@PathVariable String token) { // ,@PathVariable
																		// String
																		// account
		// response.setContentType("text/html;charset=utf-8");
		// response.setStatus(HttpServletResponse.SC_OK);
	 
		
		
		String result = "error";
		String msgSignature = request.getParameter("msg_signature");
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");
		String echostr = request.getParameter("echostr");
		myWxCpService.setRequest(request);
		
		System.out.println("msgSignature===" + province+"==="+token);
		
		System.out.println("msgSignature===" + msgSignature);
	 
		DodemWxServer  myService=  myWxCpService.getWxCpServiceByPT(province, token);
		
		WxCpConfigStorage config=myService.getConfig();
		
		if (StringUtils.isNotBlank(echostr)) {
		//	if (!myWxCpService.getWxCpServiceByPT(provience,token).checkSignature(msgSignature, timestamp, nonce, echostr)) {
			if (!myService.checkSignature(msgSignature, timestamp, nonce, echostr)) {	
				
				// 消息签名不正确，说明不是公众平台发过来的消息
				// response.getWriter().println("非法请求");
				// return;
				result = "非法请求";
			}
			 
			WxCpCryptUtil cryptUtil = new WxCpCryptUtil(config);
			String plainText = cryptUtil.decrypt(echostr);
			 log.debug(plainText);
			// 说明是一个仅仅用来验证的请求，回显echostr
			// response.getWriter().println(plainText);

			// return;
			result = plainText;
		} else if (StringUtils.isNotBlank(msgSignature)) {

			WxCpXmlMessage inMessage = null;
			try {
				inMessage = WxCpXmlMessage.fromEncryptedXml(request.getInputStream(), config,
						timestamp, nonce, msgSignature);
				WxCpXmlOutMessage outMessage = myWxCpService.getWxCpMessageRouter().route(inMessage);
				System.out.println("inMessage=================\n" + inMessage.getContent());
				if (outMessage != null) {
					// response.getWriter().write(outMessage.toEncryptedXml(myWxCpService.getConfig()));
					result = outMessage.toEncryptedXml(config);
				}
				// return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = e.getMessage();
			}

		} else {
			result = "该接口为微信接口，请勿直接访问！";
			// response.getWriter().println("该接口为微信接口，请勿直接访问！");
		}
		System.out.println("rrrr=================\n" + result);
		return result;
	}
	public String getWeatherInfo(String prvinceid){
		//http://op.juhe.cn/onebox/weather/query?cityname=北京&key=15567e968be6a90743ea6d1ce0f5df11
		//http://mobile.weather.com.cn/data/forecast/%s.html
		String _url = null;
		try {
			_url = String.format( "http://op.juhe.cn/onebox/weather/query?cityname=%s&key=15567e968be6a90743ea6d1ce0f5df11",java.net.URLEncoder.encode(prvinceid,"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String str= "";  
		  log.debug("==========================================\n\n");
	    log.debug(_url);
		try {
		   	  URL url= new URL(_url );
		    	 log.debug(url.getQuery());
		    	 log.debug(url.toString());
			  BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));//解决乱码问题  
              StringBuffer sb = new StringBuffer();  
              String s = "";  
              while ((s = br.readLine()) != null) {  
                  sb.append(s + "\r\n"); //将内容读取到StringBuffer中  
              }  
              log.debug(sb);
              br.close();  
              //System.out.println(sb.toString()); 屏幕  
              str = new String(sb.toString().getBytes());
              
              log.warn(JSONObject.parseObject(sb.toString()));
            
              
              //str=sb.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{ 
		}
		
		
		
		return str;
	}
	
	/**
	 * 根據城市ID讀取城市天氣
	 * 
	 * */
	@RequestMapping(value = "/eqweather/{prvinceid}", produces = "text/html;charset=UTF-8")
	public @ResponseBody  String geteqweather(HttpServletRequest request,@PathVariable String prvinceid){
	
	 
		Wxprovinceids winf=	weatherDao.getWeatherInfo(prvinceid);
		
		return winf.getWeatherinfo(); 
	}
	@RequestMapping(value = "/eqwareaname", produces = "text/html;charset=UTF-8")
	public @ResponseBody  String geteqweatherByAreaName(HttpServletRequest request,@RequestParam(value = "areaname") String areaname){
	
	 
		Wxprovinceids winf=	weatherDao.getWeatherInfoByAreaName(areaname);
		
		return winf.getWeatherinfo(); 
	}
	
	
	
	
	
	/**
	 * 根據城市ID讀取城市天氣
	 * 
	 * */
	@RequestMapping(value = "/weather/{prvinceid}", produces = "text/html;charset=UTF-8")
	public @ResponseBody  String getweather(HttpServletRequest request,@PathVariable String prvinceid){
 
		return getWeatherInfo(prvinceid); 
	}
	
	@RequestMapping(value = "/get_weatherinfo")
	public @ResponseBody  JSONObject getWeatherInfo(HttpServletRequest request ){
		 JSONObject obj=new JSONObject();
		 List<Wxprovinceids> items=weatherDao.getUsedInfo();
 
			for(Wxprovinceids item:items){
	 
				 obj.put(item.getAreaname(),JSONObject.parse(item.getWeatherinfo()) );
			}
		 
 
 	  
 
		return obj;
	 
	}
	
	
	@RequestMapping(value = "/sync_weatherinfo")
	public @ResponseBody  JSONObject syncWeatherInfo(HttpServletRequest request ){
		JSONObject obj=new JSONObject();
		 List<Wxprovinceids> items=weatherDao.getUsedProvince();
 
			int i=0;
			for(Wxprovinceids item:items){
 
				String winf= getWeatherInfo(item.getAreaname());
 
				 item .setWeatherinfo(winf);
				 items.set(i, item);
				 i++;
				 winf=null;
			}
        obj.put("success", true);
        
 	 	weatherDao.updateWeatherInfo(items);
 
		return obj;
	 
	}
	
	
}
